// pages/mainMusic/mainMusic.js
import { getBannerList, getSongMenu, getSongRecommend } from '../../service/request/main'
import rankingStore from '../../store/ranking'
import recommendStore from '../../store/recommend'
Page({
  data: {
    searchValue: "",
    banners: [],
    songs: [],
    hotSongMenu: [],
    reCommendSongMenu: [],
    rankingList: {},
    showRecommend: false,
    showRanking: false
  },
  onLoad() {
    // 获取banner
    this.fetchBanner()
    // 获取歌单
    this.fetchSongMenu()
    // 获取歌曲列表
    recommendStore.dispatch("fetchSongsRecomendAction")
    recommendStore.onState("recommend", (value) => {
      if(value.tracks) {
        this.setData({songs: value.tracks.slice(0, 5)})
        this.setData({showRecommend: true})
      }
    })
    // 获取巅峰列表
    rankingStore.dispatch("fetchRankingList")
    rankingStore.onState("newRanking",this.handleRanking("newRanking"))
    rankingStore.onState("originRanking",this.handleRanking("originRanking"))
    rankingStore.onState("uperRanking",this.handleRanking("uperRanking"))
  },
  
  // 搜索框点击
  searchClick() {
    wx.navigateTo({url: '/pages/mainSearch/mainSearch'})
  },
  // 轮播图
  async fetchBanner() {
    const res = await getBannerList()
    this.setData({banners: res.banners})
  },
  //更多页
  moreRecomend() {
    wx.navigateTo({
      url: '/pages/mainDetail/mainDetail?type=recommend',
    })
  },
  // 获取热门歌单
  fetchSongMenu() {
    // 热门歌单
    getSongMenu().then(res => {
      // console.log(res.playlists);
      this.setData({hotSongMenu: res.playlists})
    })
    // 推荐歌单
    getSongMenu("华语").then(res => {
      // console.log(res.playlists);
      this.setData({reCommendSongMenu: res.playlists})
    })

  },
  // 更新操作
  handleRanking(rankingName) {
    return value => {
      if(!value.name)return
      const Ranking = { ...this.data.rankingList, [rankingName]: value}
      if(Object.keys(Ranking).length === 3) {
        this.setData({showRanking: true})
      }
      this.setData({rankingList: Ranking})
    }
  }
})